/* This file creates inputs for the reduced-form analysis for the longer panel  */

********** Create the inputs to construct exovmktsh, exovsysh, etc.
clear all
set more off
cd ""   //targed directory

clear
use "./prepare/allbasic_oldyrs.dta",clear
keep if year>1999
keep id year vnd
replace year=year-1
rename vnd adj_vnd
tempfile adjvnd
save `adjvnd'


clear
use "./prepare/allbasic.dta",clear
keep if year==2006
replace year=year-1
keep id year prechs
rename prechs adj_vnd
append using `adjvnd'
tempfile adj_vnd
save `adj_vnd'


clear
use "./prepare/allbasic_oldyrs",clear
merge 1:1 id year using `adj_vnd'
keep if _merge==3
drop _merge
rename vnd prechs
append using "./prepare/allbasic.dta",force

sort ahaid year
outfile ahaid year prechs adj_vnd hsa sysid bdtot using "./prepare/input4createIV_oldyrs",c replace






********** Create inputs for IV estimation
clear
use "./prepare/allbasic_oldyrs.dta",clear
keep if year>1999
keep id year vnd
replace year=year-1
rename vnd adj_vnd
tempfile adjvnd
save `adjvnd'


clear
use "./prepare/allbasic.dta",clear
keep if year==2006
replace year=year-1
keep id year prechs
rename prechs adj_vnd
append using `adjvnd'
tempfile adj_vnd
save `adj_vnd'


clear
use "./prepare/allbasic_oldyrs",clear
merge 1:1 id year using `adj_vnd'
keep if _merge==3
drop _merge
rename vnd prechs
append using "./prepare/allbasic.dta",force


bys sysid year hsa:gen nhsa_persys = _n == 1
replace nhsa_persys=0 if sysid==0
bys sysid year:replace nhsa_persys = sum(nhsa_persys)
bys sysid year:replace nhsa_persys = nhsa_persys[_N]
bys hsa year:egen with_mulrsys=max(nhsa_persys>1)
gen sa=0
replace sa=1 if prechs==1 &adj_vnd>1& sysid==0
bys hsa year:egen with_sa=max(sa==1)
keep if with_mulrsys>0&with_sa>0
drop if sysid==0
keep if nhsa_persys>1
duplicates drop hsa year sysid,force
sort hsa year sysid
outfile hsa year sysid using "./prepare/sysyr", c replace


